<?php
require_once("inc.member.php");
$this_title="$vars[member_title] &raquo; ".__("Profile");
$page_title=__("Profile");
$content_title=__("Profile");

$r_gender_d=array("f"=>__("Female"), "m"=>__("Male"));
$country_code=$vars['common']['country_code'];
array_shift($country_code);
$country_code_t=$vars['common']['country_code_text'];
foreach($country_code_t as $code=>$cname){
 $country_code_d[$code]=__($cname);
}

require_once("inc.profile_tab.php");

$td_width=180;

//#####CHANGE PASSWORD POST#####
if($_POST["__req"] && ($_GET["p"]=='1' || $_GET["p"]=='2' || $_GET["p"]=='3')){
 if($post_s['__req']=='1' || $post_s['__req']=='2' || $post_s['__req']=='3'){//password
  $errmsg=verify_form_data("users", $post_s);
  if(!$errmsg){
   if(!strlen($post_s["old_password"])){
    $errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Existing Password")))."<br />\n";
   }else{	
   		if($post_s['__req']=='1')
    		$enc_pass=explode(":", $r_user["enc_password"]);    
    	elseif($post_s['__req']=='2')
    	   	$enc_pass=explode(":", $r_user["ewallet_enc_password"]);    
    		$enc_pass3=explode(":", $r_user["epoint_enc_password"]);
			
    	$salt=$enc_pass[1];
    	if(md5($post_s["old_password"].$salt)!=$enc_pass[0]){
     		$errmsg.=__("You have entered an invalid Existing Password.")."<br />\n";
    	}    	    	
    	
    	$salt=$enc_pass[1];    	
    	if(md5($post_s["password3"].$salt)!=$enc_pass[0]){     		
    		$errmsg.=__("You have entered an invalid Level 2 Password.")."<br />\n";    	
    	}
   }
   if(!is_alphanum($post_s["_password"])){
    $errmsg.=replace_tag(__("'<%field%>' must be a combination of numbers and alphabets."), array("<%field%>"=>__("Password")))."<br />\n";
   }elseif(!$post_s["password2"]){
    $errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Confirm Password")))."<br />\n";
   }elseif($post_s["password2"]!=$post_s["_password"]){
    $errmsg.=__("Your entered passwords did not match.")."<br />\n";
   }
  } }else{//security password
  $errmsg=verify_form_data("users", $post_s);
  if(!$errmsg){
   if(!strlen($post_s["old_sec_password"])){
    $errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Existing Security Password")))."<br />\n";
   }else{
    $enc_pass=explode(":", $r_user["enc_sec_password"]);
    $salt=$enc_pass[1];
    if(md5($post_s["old_sec_password"].$salt)!=$enc_pass[0]){
     $errmsg.=__("You have entered an invalid Existing Security Password.")."<br />\n";
    }
   }
   if(!is_alphanum($post_s["_sec_password"])){
    $errmsg.=replace_tag(__("'<%field%>' must be a combination of numbers and alphabets."), array("<%field%>"=>__("Security Password")))."<br />\n";
   }elseif(!$post_s["sec_password2"]){
    $errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Confirm Security Password")))."<br />\n";
   }elseif($post_s["sec_password2"]!=$post_s["_sec_password"]){
    $errmsg.=__("Your entered security passwords did not match.")."<br />\n";
   }
  }
 }

 //#####UPDATE TO DB#####
 if(!$errmsg){
  $salt=generate_random_code(32);
  if($post_s['__req']=='1'){
   $enc_password=md5($post_s["_password"].$salt).":".$salt;
   $password_q="password='$post_d[_password]', enc_password='$enc_password'";  
  }elseif($post_s['__req']=='2'){   
   $enc_password=md5($post_s["_password"].$salt).":".$salt;   
   $password_q="ewallet_password='$post_d[_password]', ewallet_enc_password='$enc_password', epoint_password='$post_d[_password]', epoint_enc_password='$enc_password'";  
  }elseif($post_s['__req']=='3'){   
   $enc_password=md5($post_s["_password"].$salt).":".$salt;   
   $password_q="epoint_password='$post_d[_password]', epoint_enc_password='$enc_password'";
  }else{
   $enc_password=md5($post_s["_sec_password"].$salt).":".$salt;
   $password_q="sec_password='$post_d[_sec_password]', enc_sec_password='$enc_password'";
  }
  $update_pass_q=$r_user["update_pass"]=="y"? ", update_pass=''" : "";
  $sql="update $db->users set $password_q $update_pass_q where id='$uid' limit 1";
  if(!mysql_query($sql)){
   $errmsg.=__("We have encountered some error and the update process has been failed.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
  }
  if(!$errmsg){	if($post_s['__req']=='2'){		
  	$msg=__("You have successfully updated your level 2 password.")."<br />\n";		
  	$ewallet_msg=$msg? format_msg($msg) : "";	
  }elseif($post_s['__req']=='3'){		
  	$msg=__("You have successfully updated your e-Stockist account password.")."<br />\n";		
  	$epoint_msg=$msg? format_msg($msg) : "";	
  }else{
	   $msg=format_msg(__("You have successfully updated your level 1 password.").($post_s['__req']=='1'? " ".__("You will need to re-login to your account.")." ".__("Please click on the below button to login.") : "")).	
	   ($post_s['__req']=='1'? "<br />\n<br />\n	
	   <p class='center'><input type='button' value=\"".__("Login")."\" onclick=\"window.location='".M_URL."/".$vars["file"]["public"]["index"]."';\" /></p>" : "");	
	   $msg=str_replace("<%tab_content%>", $msg, $tab);	
	   print format_member_page("<h2>$page_title</h2>".$msg, $this_title, $css);	}
  }
 } 
 
 if($post_s['__req']=='2'){ 	
 	$ewallet_errmsg=$errmsg? format_err($errmsg) : ""; 
 }elseif($post_s['__req']=='3'){ 	
 	$epoint_errmsg=$errmsg? format_err($errmsg) : ""; 
 }else{
 	$p_errmsg=$errmsg? format_err($errmsg) : ""; 
 }
 $errmsg='';
}

//#####CHANGE DETAIL POST#####
if($_POST["__req"] && !$_GET["p"]){
 /*##### ERROR CHECK #####*/
 $chk_arr="_email,_address,_address2,_city,_zip,_state,_mobileno,_officeno,_faxno,_bank_name,_bank_acc_no,_bank_swiftcode,_bank_branch,_payee_name";
 if($r_user["acc_type"]=="p"){
  $chk_arr.=",_homeno";
 }else{
  $chk_arr.=",_person_in_charge";
 }
 $chk_arr=explode(",", $chk_arr);
 foreach($post_s as $f=>$v){
  if(in_array($f, $chk_arr)){
   $data[$f]=$v;
  }
 }
 $errmsg=verify_form_data("users", $data);
 if(!$errmsg){
  if($r_user["acc_type"]=="p"){
   //check dob
   $dob="$post_s[dob_year]-".pad_length($post_s["dob_month"], 2)."-".pad_length($post_s["dob_day"], 2);
   if(!@checkdate($post_s["dob_month"], $post_s["dob_day"], $post_s["dob_year"])){
    $errmsg=__("Invalid date format selected for DOB.")."<br />\n";
   }
  }
  //check password
  if(!strlen($post_s["password"])){
   $errmsg.=__("Please provide your level 2 password.")."<br />\n";
  }else{
   $enc_pass=explode(":", $r_user["ewallet_enc_password"]);
   $salt=$enc_pass[1];
   if(md5($post_s["password"].$salt)!=$enc_pass[0]){
    $errmsg.=__("You have entered an invalid level 2 password.")."<br />\n";
   }
  }
  //check email
  if(strlen($post_s['_email'])){
	  if(!verify_email($post_s["_email"])){
	   $errmsg.=__("Please provide a valid email address.")."<br />\n";
	  }elseif($post_s['_email'] != $r_user['email'] && email_found($post_d['_email'])){
	   $errmsg.=replace_tag(__("The email address '<%email%>' is already in use, please providee another."), array("<%email%>"=>$post_h['_email']))."<br />\n";
	  }
  }
 }
 //#####END ERROR CHECK#####

 //#####UPDATE TO DB#####
 if(!$errmsg){
  $update_arr=implode(",", $chk_arr);
  //khor 20100602: no need to update country
  //$update_arr.=",dob,country";
  $update_arr.=",dob";
  $post_s['dob']=$post_d['dob']=$dob;
  $update_arr=explode(",", $update_arr);
  foreach($update_arr as $field){
   $db_field=substr($field, 0, 1)=="_"? substr($field, 1) : $field;
   $ufvq.=($ufvq? ", " : "")."$db_field='".$post_d[$field]."'";
  }
  $sql="update $db->users set $ufvq where id='$uid' limit 1";
  if(!mysql_query($sql)){
   $errmsg.=__("We have encountered some error and the update process has been failed.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
  }
  if(!$errmsg){
   $msg=__("You have successfully updated your account information.")."<br />\n";
  }
 }

 $i_msg=$msg? format_msg($msg) : "";
 $i_errmsg=$errmsg? format_err($errmsg) : "";
 $errmsg=$msg='';
}

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('a[@name=tab]').click(function(){
  var ptype=j(this).attr('rel');
  j('div#profile_info').css('display', ptype=='info'? 'block' : 'none');
  j('div#profile_pass').css('display', ptype=='pass'? 'block' : 'none'); 
  j('div#profile_ewallet_pass').css('display', ptype=='ewallet'? 'block' : 'none'); 
  j('div#profile_epoint_pass').css('display', ptype=='epoint'? 'block' : 'none');
  j('ul#_tab > li').removeClass().addClass('tabs-unselected');
  j(this).parent().removeClass().addClass('tabs-selected');
  return false;
 });
 j('form[@name=profile_pass_form],form[@name=profile_ewallet_pass_form],form[@name=profile_epoint_pass_form],form[@name=profile_info_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });
});

function makeEnable(){
    var x=document.getElementById('country');
    x.disabled=false;
}
</script>";

//change password form
if($get_s["p"]=='1')
	$form_fields=array("old_password"=>__("Existing Password"),"_password"=>__("New Password"),"password2"=>__("Confirm Password"), "password3"=>__("Level 2 Password"));
else
	$form_fields=array("old_password"=>__("Existing Password"),"_password"=>__("New Password"),"password2"=>__("Confirm Password"), "password3"=>__("Level 1 Password"));
foreach($form_fields as $field => $fname){
 $extra_display="";
 if($field=="_password"){
  $pass_dt=explode("#", $vars["dbr"]["users"]["password"]);
  $extra_display="<br />\n".replace_tag(__("Password must be at least <%min%> <%character%> long, and must be a combination of numbers and alphabet."), array("<%min%>"=>$pass_dt[1], "<%character%>"=>$pass_dt[1]>1? __("characters") : __("character")));
 }
 
 if($field=="password3"){
 	if($get_s["p"]=='2')
 		$placeholder=__("Need provide level 1 password to update!");
 	else
 		$placeholder=__("Need provide level 2 password to update!");
 }
 
 $form_inputfield[$field]='
  	<div class="form-group">
	<label for="disabledinput" class="col-sm-3 control-label">'.__($fname).'</label>
	<div class="col-sm-6">
		<input type="password" class="form-control" id="'.$field.'" name="'.$field.'" value="'.$dis[$field].'" placeholder="'.$placeholder.'">
	</div>
	</div>';
}

$profile_pass=($p_errmsg? $p_errmsg : "").
'<div class="panel panel-primary">
				      <form class="form-horizontal" name="profile_pass_form" method="post" action="'.$this_file.'?p=1">
					  <input type="hidden" name="__req" value="1" />
				      <div class="panel-heading">
				          <h4>'.__("Level 1 Password").'</h4>				          
				      </div>
				      <div class="panel-body">'.
				       	$form_inputfield['old_password'].
 						$form_inputfield['_password'].
						$form_inputfield['password2'].
						$form_inputfield['password3'].
				      '<div class="panel-footer">
				      	<div class="row">
				      		<div class="col-sm-6 col-sm-offset-3">
				      			<div class="btn-toolbar">
					      			<input type="submit" name="submit_btn" value="'.__("Update").'" onclick="makeEnable();"/>
				      			</div>
				      		</div>
				      	</div>
				      </div>
				  </form>
				  </div>
</div>
';

$profile_ewallet_pass=($ewallet_errmsg||$ewallet_msg? $ewallet_errmsg.$ewallet_msg : "").
'<div class="panel panel-primary">
				      <form class="form-horizontal" name="profile_pass_form" method="post" action="'.$this_file.'?p=2">
					  <input type="hidden" name="__req" value="2" />
				      <div class="panel-heading">
				          <h4>'.__("Level 2 Password").'</h4>				          
				      </div>
				      <div class="panel-body">'.
				       	$form_inputfield['old_password'].
 						$form_inputfield['_password'].
						$form_inputfield['password2'].
						$form_inputfield['password3'].
				      '<div class="panel-footer">
				      	<div class="row">
				      		<div class="col-sm-6 col-sm-offset-3">
				      			<div class="btn-toolbar">
					      			<input type="submit" name="submit_btn" value="'.__("Update").'" onclick="makeEnable();"/>
				      			</div>
				      		</div>
				      	</div>
				      </div>
				  </form>
				  </div>
</div>
';

$profile_epoint_pass=($epoint_errmsg||$epoint_msg? $epoint_errmsg.$epoint_msg : "").
"<h3>".__("e-Stockist Password")."</h3>".($_GET["f"]?
"<p class='bold'>".__("You must update your password to continue since the existing password is a temporary password and this will better protect andsecure your account.")."</p>" : "").
"<form name='profile_epoint_pass_form' method='post' action='$this_file?p=3'>
<input type='hidden' name='__req' value='3' />
<table class='pbt_table'>
	$form_inputfield[old_password]
	$form_inputfield[_password] 
	$form_inputfield[password2] 
	<tr>  
		<td colspan='2' class='center' style='padding:20px 0 20px 0;'>   
		<input type='submit' name='submit_btn' value=\"".__("Update")."\" />
		</td>
	</tr>
</table>
</form>";

//change info form
$form_fields=array("_person_in_charge"=>$r_user["person_in_charge"],"_bis_reg"=>$r_user["bis_reg"],"_name"=>$r_user["name"],"_email"=>$r_user["email"],"_ic"=>$r_user["ic"],"_address"=>$r_user["address"],"_address2"=>$r_user["address2"],"_city"=>$r_user["city"],"_zip"=>$r_user["zip"],"_state"=>$r_user["state"],"country"=>$r_user["country"],"_homeno"=>$r_user["homeno"],"_mobileno"=>$r_user["mobileno"],"_officeno"=>$r_user["officeno"],"_faxno"=>$r_user["faxno"],"dob_day"=>date("j", strtotime($r_user["dob"])),"dob_month"=>date("n", strtotime($r_user["dob"])),"dob_year"=>date("Y", strtotime($r_user["dob"])),"gender"=>$r_user["gender"],"_bank_name"=>$r_user["bank_name"],"_bank_acc_no"=>$r_user["bank_acc_no"],"_bank_swiftcode"=>$r_user["bank_swiftcode"],"_bank_branch"=>$r_user["bank_branch"],"_payee_name"=>$r_user["payee_name"]);
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=!$post_s["__req"] || $get_s["p"]? $default : $post_h[$field];
}

//khor 20100602: disable member to change country
//$country_select=build_select($country_code, $country_code_d, $dis["country"], "country", $inputbox_style);
$country_select=build_select($country_code, $country_code_d, $dis["country"], "country", "disabled class='form-control'");
$dob_input=generate_dmy_input("dob", $dis["dob_day"], $dis["dob_month"], $dis["dob_year"], "class='form-control'");

$display_fields=array("_person_in_charge","_bis_reg","_name","_email","_ic","_address","_address2","_city","_zip","_state","_homeno","_mobileno","_officeno","_faxno","_bank_name","_bank_acc_no","_bank_swiftcode","_bank_branch","_payee_name");
foreach($form_fields as $field => $default){
 if(in_array($field, $display_fields)){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dbr=explode("#", $vars["dbr"]["users"][$db_fieldname]);
  $readonly=$textarea=$password=false;
  $add_class="";
  if(in_array($field, array("_name","_ic","_bis_reg"))){
   $readonly=true;
  }
  if($field=="_bank_acc_no"){
   /*$extra_display="<br />\n".replace_tag(__("If you wish to change your payment information, you will need to contact us."), array("<%link%>"=>"<a href='".$vars["file"]["public"]["contactus"]."'>", "<%/link%>"=>"</a>", "<%contact us%>"=>__("Contact Us")));*/
  }else{
   $extra_display="";
  }
  $readonly_str=$readonly? "readonly='readonly'" : "";
  $add_class=$readonly? "readonly" : "";
  $inputbox_style2=$add_class? preg_replace('/^class=\'/', "class='$add_class ", $inputbox_style) : $inputbox_style;
  
  $form_inputfield[$db_fieldname]='
  	<div class="form-group">
	<label for="disabledinput" class="col-sm-3 control-label">'.__($dbr[4]).'</label>
	<div class="col-sm-6">
		<input type="text" class="form-control" id="'.$field.'" name="'.$field.'" value="'.$dis[$field].'">
	</div>
	</div>';
 }
}

$profile_info=($i_errmsg || $i_msg? $i_errmsg.$i_msg : "").'

				<div class="panel panel-primary">
					<form class="form-horizontal" method="post" action="'.$this_file.'">
					<input type="hidden" name="__req" value="1" />
				    <div class="panel-heading">
						<h4>'.__("Account Information").'</h4>				          
				    </div>
				    <div class="panel-body">
						<div class="form-group">
							<label for="disabledinput" class="col-sm-3 control-label">'.__('Member ID').'</label>
						    <div class="col-sm-6">
						      	<input disabled type="text" class="form-control" id="disabledinput" value="'.$r_user['code'].'">
						    </div>
						</div>'.
						$form_inputfield['name'].
						$form_inputfield['email'].
						$form_inputfield['ic'].'
						<div class="form-group">
							<label for="selector1" class="col-sm-3 control-label">'.__('Gender').'</label>
						  	<div class="col-sm-6"><select name="gender" id="gender" class="form-control">
						  		<option '.($r_user["gender"]=='f'?'selected':'').'>'.__('Female').'</option>
						  		<option '.($r_user["gender"]=='m'?'selected':'').'>'.__('Male').'</option>
						  	</select>
						  	</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">'.__("Date of Birth").'</label>
				            <div class="col-sm-6">
				            	'.$dob_input.'
				            </div>
				        </div>'.
						$form_inputfield['address'].'
						<div class="form-group">
						    <label for="focusedinput" class="col-sm-3 control-label">'.__('Country').'</label>
						    <div class="col-sm-6">
						      	'.$country_select.'
						    </div>
						</div>'.
						$form_inputfield['homeno'].
						$form_inputfield['mobileno'].
						$form_inputfield['payee_name'].
 						$form_inputfield['bank_name'].
 						$form_inputfield['bank_acc_no']. 
 						$form_inputfield['bank_swiftcode']. 
 						$form_inputfield['bank_branch'].'
						<div class="form-group">
						    <label for="disabledinput" class="col-sm-3 control-label">'.__('Level 2 Password').'</label>
						    <div class="col-sm-6">
						      <input type="password" class="form-control" id="password" name="password" placeholder="'.__('Need provide level 2 password to update!').'">
						    </div>
						</div>					  
					</div>
				    <div class="panel-footer">
						<div class="row">
				      		<div class="col-sm-6 col-sm-offset-3">
				      			<div class="btn-toolbar">
					      			<input type="submit" name="submit_btn" value="'.__("Update").'" onclick="makeEnable();"/>
				      			</div>
				      		</div>
				      	</div>
					</div>
					</form>
				</div>
';

$profile="<div id='profile_info'".($get_s["p"]? " style='display:none;'" : "").">$profile_info</div><div id='profile_pass'".
($get_s["p"]!='1'? " style='display:none;'" : "").">$profile_pass</div><div id='profile_ewallet_pass'".
($get_s["p"]!='2'? " style='display:none;'" : "").">$profile_ewallet_pass</div><div id='profile_epoint_pass'".
($get_s["p"]!='3'? " style='display:none;'" : "").">$profile_epoint_pass</div>";

$profile=($get_s["p"]? "" : $profile_info).($get_s["p"]!='1'? "" : $profile_pass).($get_s["p"]!='2'? "" : $profile_ewallet_pass);
//$profile=str_replace("<%tab_content%>", $profile, $tab);
$content=$profile;
print format_member_page($content, $this_title, $content_title, $css.$jvscript);
?>